<template>
  <div class="container">
    <!-- 搜索 -->
    <div class="mainCon">
      <el-row class="toolbar searchInputWidth" style="padding-bottom: 0">
        <el-form :inline="true" :model="filterField" ref="searchConditions">
          <el-col :lg="8" :xl="6">
            <el-form-item label="项目名称" class="row-padding-bottom">
              <el-input
                placeholder="请输入项目名称"
                clearable
                v-model="filterField.projectName"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :lg="8" :xl="6">
            <el-form-item label="项目状态" class="row-padding-bottom">
              <el-select
                v-model="filterField.projectStatus"
                filterable
                placeholder="请选择"
                clearable
              >
                <el-option
                  v-for="item in statusOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <template v-if="advanced">
            <el-col :lg="8" :xl="6">
              <el-form-item label="统一专户账号" class="row-padding-bottom">
                <el-input
                  placeholder="请输入统一专户账号"
                  clearable
                  v-model="filterField.account"
                ></el-input>
              </el-form-item>
            </el-col>
          </template>
          <el-form-item>
            <a
              @click="toggleAdvanced"
              style="margin-left: 40px; color: #409eff; cursor: pointer"
              class="btnColor"
            >
              {{ advanced ? '收起' : '展开' }}
              <i
                :class="advanced ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"
              ></i>
            </a>
            <el-button
              type="primary"
              icon="icon iconfont iconchazhao1"
              @click="searchList"
              class="searchBtn"
            >
              <span>搜索</span>
            </el-button>
          </el-form-item>
          <el-form-item>
            <el-button
              class="commonBut saveBtn funComBut"
              icon="icon iconfont icontianjia"
              @click="toAdd"
            >
              <span class="opetareText">添加</span>
            </el-button>
          </el-form-item>
        </el-form>
      </el-row>
      <!-- 表格 -->
      <el-table
        :data="tableList"
        @sort-change="sortChange"
        v-loading="loading"
        :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
        highlight-current-row
        stripe
        style="border: 1px solid #dfe6ec"
      >
        <el-table-column label="项目名称" width="230">
          <template slot-scope="scope">
            <copyText
              :tableIndex="scope.$index"
              :copyTextName="scope.row.projectName"
              :columnName="'projectName'"
            ></copyText>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="pcName" label="建设方" align="center" :formatter="formatTd"></el-table-column> -->
        <el-table-column label="建设方" width="230">
          <template slot-scope="scope">
            <copyText
              :tableIndex="scope.$index"
              :copyTextName="scope.row.pcName"
              :columnName="'pcName'"
            ></copyText>
          </template>
        </el-table-column>
        <el-table-column
          prop="projectStatusDesc"
          label="状态"
          align="center"
          :formatter="formatTd"
          min-width="100"
        ></el-table-column>
        <el-table-column
          prop="investmentDesc"
          label="投资类型"
          align="center"
          :formatter="formatTd"
          min-width="120"
        ></el-table-column>
        <el-table-column
          prop="bankName"
          label="专户统一开户行"
          align="center"
          :formatter="formatTd"
          min-width="200"
        ></el-table-column>
        <el-table-column
          prop="account"
          label="统一专户账号"
          align="center"
          :formatter="formatTd"
          min-width="200"
        ></el-table-column>
        <el-table-column
          prop="expensesTotal"
          sortable="custom"
          label="总支出（元）"
          align="center"
          :formatter="formatTd"
          min-width="180"
        ></el-table-column>
        <el-table-column
          prop="balance"
          sortable="custom"
          label="余额（元）"
          align="center"
          :formatter="formatTd"
          min-width="180"
        ></el-table-column>
        <el-table-column label="操作" align="left" fixed="right">
          <template slot-scope="scope">
            <div v-if="scope.row.isRemove">
              <el-link type="primary" @click="goOut(scope.row.id)"
                >移出</el-link
              >
            </div>
            <div v-else>--</div>
          </template>
        </el-table-column>
        <!-- 表格数据为空时，页面显示 -->
        <div slot="empty" v-show="isShow">
          <emptyTable emptyText="暂无相关信息"></emptyTable>
        </div>
      </el-table>
      <!-- 分页 -->
      <Pagination
        @getpageSize="getpageSize"
        @getpageNo="getpageNo"
        ref="pagination"
        @getList="getTableList"
        :filterField="filterField"
        :requestUrl="requestUrl"
      ></Pagination>
      <!-- 新增弹窗 -->
      <el-dialog
        title="添加项目"
        :visible.sync="formVisible"
        :close-on-click-modal="false"
        @close="closeDialog"
        custom-class="brand-dialog-min-width"
        width="550px"
        :modal-append-to-body="false"
        :append-to-body="true"
      >
        <el-form
          :model="formData"
          :rules="formRules"
          ref="formData"
          label-width="125px"
        >
          <el-form-item label="项目名称" prop="projectId">
            <el-select
              class="optionWidth"
              ref="projectSearch"
              v-model="formData.projectId"
              clearable
              filterable
              placeholder="请输入项目名称进行搜索"
              @change="ChangeSearch"
              @visible-change="visibleChangeProject"
              :filter-method="selectChange"
            >
              <el-option
                v-for="(item, index) in projectOptions"
                :key="index"
                :label="item.projectName"
                :value="index"
              ></el-option>
              <div class="block">
                <el-pagination
                  layout="prev, pager, next"
                  :total="total"
                  :current-page.sync="pageNo"
                  :page-size="pageSizeNumber"
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
                >
                </el-pagination>
              </div>
            </el-select>
            <p class="color999">注：授权项目可使用同一个专户账号</p>
          </el-form-item>
          <el-form-item label="建设方">
            <span>{{ pcName }}</span>
          </el-form-item>
          <el-form-item label="状态">
            <span>{{ statusDesc }}</span>
          </el-form-item>
          <el-form-item label="投资类型">
            <span>{{ investmentDesc }}</span>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click.native="cancelEdit('formData')" class="cancel"
            >取消</el-button
          >
          <el-button
            type="primary"
            @click.native="submitForm('formData')"
            class="save"
            :loading="isSaveLoading"
            >保存</el-button
          >
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { mapActions, mapState } from 'vuex'
export default {
  name: 'accountManageDetail',
  props: ['companyName', 'uscc'],
  data() {
    return {
      titleText: '企业专户管理',
      advanced: false,
      titleExplain:
        '设置项目:该企业作为施工方关联的项目由监察部门控制是否可以使用 同一专户账号,可对部分项目开放该特权',
      topAccountInfo: '',
      projectName: '', //企业名称
      requestUrl: 'api-acc/accountprojectgrant/expand/findgrantbyuscc',
      //表格数据
      tableList: [],
      isShow: false, //列表加载
      loading: false,
      companyAccountId: '',
      filterField: {
        account: '',
        projectName: '',
        projectStatus: '',
        companyName: '',
        uscc: '',
      },
      pageSize: 20,
      pageNo: 1,
      formVisible: false,
      isSaveLoading: false, // 弹框保存loading
      id: '',
      projectOptions: [], //企业名称下拉框
      projectSelect: '',
      item: '', //当前选中项
      total: 0, //企业名称总数
      pageNo: 1,
      pageSizeNumber: 20,
      pcName: '',
      statusDesc: '',
      investmentDesc: '',
      formData: {
        projectId: '',
      },
      state: '',
      formRules: {
        projectId: [
          {
            required: true,
            message: '项目名称不能为空',
            trigger: 'change',
          },
        ],
      },
    }
  },
  created() {
    this.filterField.companyName = this.companyName
    this.filterField.uscc = this.uscc
    this.getStatus({})
    this.$nextTick(function () {
      this.$refs.pagination.getTableListData()
    })
  },
  computed: {
    ...mapState(['statusOptions']),
  },
  methods: {
    toggleAdvanced() {
      this.advanced = !this.advanced
    },
    getpageSize(val) {
      this.pageSize = val
    },
    getpageNo(val) {
      this.pageNo = val
    },
    ...mapActions(['getStatus']),
    getAccountTopInfo() {
      this.axios({
        method: 'post',
        url: 'api-acc/companyaccount/expand/findCompanyAccountDetail',
        data: {
          companyAccountId: this.companyAccountId,
        },
      })
        .then((response) => {
          if (!response.data.hasError) {
            this.topAccountInfo = response.data.result
          }
        })
        .catch((error) => {
          // this.$message.error("数据获取失败");
        })
    },
    getTableList(data) {
      this.tableList = data
      this.loading = false
      if (this.tableList.length < 1) {
        this.isShow = true
      }
    },
    // 搜索
    searchList() {
      this.$refs.pagination.getTableListData()
    },
    goBack() {
      this.$router.push({
        path: '/home/yiChangCustomRequirements/enterpriseAccountManage',
      })
      this.$store.commit('GOBACK_NAME', {
        oldUrl: '/home/yiChangCustomRequirements/enterpriseAccountManage',
        newUrl: this.$router.currentRoute.fullPath,
      })
    },
    //移出
    goOut(id) {
      this.$confirm(
        '是否确认移出该项目？移出后该项目将无法使用统一专户，系统将会通知相关企业以及项目，请谨慎操作。',
        '提醒',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      )
        .then(() => {
          this.goOutConfirm(id)
        })
        .catch(() => {})
    },
    // 确认移出
    goOutConfirm(id) {
      this.axios({
        method: 'post',
        url: 'api-acc/companyaccount/expand/removeProject',
        data: {
          accountProjectGrantId: id,
        },
      })
        .then(
          (res) => {
            if (!res.data.hasError) {
              this.$message({
                type: 'success',
                message: '移出成功!',
              })
              this.$refs.pagination.getTableListData(this.pageNo, this.pageSize)
            } else {
              this.$message({
                type: 'error',
                message: res.data.errorMsg,
              })
            }
          },
          (response) => {
            this.$message({
              type: 'error',
              message: '数据请求失败',
            })
          }
        )
        .catch((res) => {})
    },
    toAdd() {
      this.formVisible = true
      this.pcName = ''
      this.statusDesc = ''
      this.investmentDesc = ''
      if (this.uscc) {
        this.getCompanyList(this.pageNo, this.pageSizeNumber)
      }
    },
    getCompanyList(pageNo, pageSizeNumber, val) {
      this.axios({
        method: 'post',
        url: 'api-acc/companyaccount/expand/findProjectListByUscc',
        data: {
          pageNo: pageNo,
          pageSize: pageSizeNumber,
          projectName: val,
          uscc: this.uscc,
        },
      })
        .then(
          (response) => {
            if (!response.data.hasError) {
              this.projectOptions = response.data.result.results
              this.total = response.data.result.total
            } else {
            }
          },
          (response) => {}
        )
        .catch((error) => {})
    },
    ChangeSearch() {
      // 自动获取焦点
      this.$nextTick(() => {
        this.$refs.projectSearch.blur()
      })
      this.item = this.projectOptions[this.formData.projectId]
      console.log('item', this.item)
      if (this.item) {
        this.pcName = this.item.pcName
        this.statusDesc = this.item.statusDesc
        this.investmentDesc = this.item.investmentDesc
      } else {
        this.pcName = ''
        this.statusDesc = ''
        this.investmentDesc = ''
      }
    },
    //选择企业
    visibleChangeProject(val) {
      if (!this.formData.projectId && this.formData.projectId !== 0) {
        if (val) {
          this.pageNo = 1
          this.projectSelect = ''
          this.formData.projectId = ''
          this.getCompanyList(
            this.pageNo,
            this.pageSizeNumber,
            this.projectSelect
          )
        }
      } else {
        //手动输入再次打开弹框清空输入值
        // 获取的企业数据索引
        // 选中的企业的具体数据
        if (typeof this.formData.projectId === 'string') {
          this.formData.projectId = ''
        } else {
        }
      }
    },
    selectChange(val) {
      //手动输入掉接口会清空问题下拉框的值，掉完接口再赋值
      this.projectSelect = val
      this.getCompanyList(1, this.pageSizeNumber, val)
      if (typeof this.formData.projectId === 'string') {
        this.formData.projectId = val
      }
      this.formData.projectId = val
    },
    handleSizeChange(val) {},
    handleCurrentChange(val) {
      this.getCompanyList(val, this.pageSizeNumber, this.projectSelect)
      this.formData.projectId = ''
      this.pcName = ''
      this.statusDesc = ''
      this.investmentDesc = ''
    },
    //关闭弹窗
    closeDialog() {
      this.$refs['formData'].resetFields()
    },
    // 弹框取消
    cancelEdit() {
      this.formVisible = false
      this.$refs['formData'].resetFields()
    },
    submitForm(formName) {
      this.$refs.formData.validate((valid) => {
        if (valid) {
          this.isSaveLoading = true
          this.submitFormAdd()
        } else {
          return false
        }
      })
    },
    submitFormAdd() {
      console.log(8888, this.item)
      this.axios({
        method: 'post',
        url: 'api-acc/companyaccount/expand/saveAccountProjectInfo',
        data: {
          // companyAccountId: this.filterField.companyAccountId,
          projectId: this.item.id,
          projectName: this.item.projectName,
          pcName: this.item.pcName,
          status: this.item.status,
          investment: this.item.investment,
          uscc: this.uscc,
        },
      })
        .then((response) => {
          this.isSaveLoading = false
          if (!response.data.hasError) {
            this.$message({
              message: '保存成功',
              type: 'success',
            })
            this.$refs['formData'].resetFields()
            this.formVisible = false
            this.$refs.pagination.getTableListData()
          } else {
            this.$message({
              type: 'error',
              message: response.data.errorMsg,
            })
            this.isSaveLoading = false
          }
        })
        .catch((error) => {
          this.$message.error('保存失败')
          this.isSaveLoading = false
        })
    },
    toAccountFlow() {
      this.$router.push({
        path: '/home/yiChangCustomRequirements/accountManageDetailFlow',
        name: 'accountManageDetailFlow',
        query: {
          account: this.topAccountInfo.account,
          id: this.companyAccountId,
        },
      })
      this.$store.commit('CHANGE_SLIDER_NAME', {
        oldUrl: '/home/yiChangCustomRequirements/enterpriseAccountManage',
        newUrl: this.$router.currentRoute.fullPath,
      })
    },
  },
}
</script>

<style lang="less" scoped>
.titleBox {
  background: #e4ebf1;
  padding: 15px 24px;
  margin: 24px;
  .blockTitle {
    font-weight: bold;
    font-size: 18px;
    color: #333;
    line-height: 40px;
    .iconfanhui1 {
      font-size: 20px;
      margin-right: 6px;
      cursor: pointer;
    }
  }
  .code {
    font-size: 14px;
    color: #666;
    margin-left: 30px;
  }
  .seeAccountDetail {
    font-size: 14px;
    color: #66b1ff;
    margin-left: 30px;
    cursor: pointer;
  }
}
.mainCon {
  top: 0px;
  padding-top: 0;
}
@import '../../../static/css/filterArea.less';
</style>
